package com.wdemo.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wdemo.enums.ChatTypeEnum;
import com.wdemo.mapper.ChatSessionMapper;
import com.wdemo.pojo.domain.ChatSession;
import com.wdemo.pojo.vo.MessageVo;
import com.wdemo.pojo.vo.SessionVO;
import com.wdemo.service.ChatHistoryService;
import com.wdemo.utils.MessageUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.messages.Message;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName ChatHistoryServiceImpl
 * @Description TODO
 * @Author WDEMO
 * @Date 2025/8/29 18:47
 */
@Service
@RequiredArgsConstructor
public class ChatHistoryServiceImpl implements ChatHistoryService {

    private final ChatSessionMapper chatSessionMapper;

    private final StringRedisTemplate stringRedisTemplate;
    @Override
    public List<SessionVO> getHistoryChatIds(String type) {
        LambdaQueryWrapper<ChatSession> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ChatSession::getUserId, 1L);
        lambdaQueryWrapper.eq(ChatSession::getType,type);
        List<ChatSession> chatSessions = chatSessionMapper.selectList(lambdaQueryWrapper);

        List<SessionVO> sessionVOList = chatSessions.stream().map(chatSession -> SessionVO.builder()
                .sessionId(chatSession.getSessionId())
                .title(chatSession.getTitle())
                .build()).collect(Collectors.toList());
        return sessionVOList;
    }

    @Override
    public List<MessageVo> getHistoryContest(String type, String chatId) {
        if (ObjectUtil.isNull(chatId) || ObjectUtil.isNull(type))
            return List.of();
        ChatTypeEnum chatTypeEnum = ChatTypeEnum.fromString(type);
        String key = chatTypeEnum.getType() + ":" + chatId;
        List<String> messageJson = stringRedisTemplate.opsForList().range(key, 0, -1);

        if (CollUtil.isEmpty(messageJson))
            return List.of();

        List<Message> messages = messageJson.stream().map(m -> MessageUtil.toMessage(m))
                .collect(Collectors.toList());
        List<MessageVo> messageVoList = messages.stream().map(message ->new MessageVo(message))
                .collect(Collectors.toList());

        return messageVoList;
    }
}
